<template>
  <v-app>
    <div class="preview-root">
      <!-- Canvas area -->
      <super-image
        v-if="currentItem"
        ref="imgviewRef"
        :selectable="active.select"
        :src="currentItem.src"
        @select="selectBox"
      >
      </super-image>
      <div
        v-if="active.list"
        class="list-box position-absolute top-0 right-0 pa-1 d-flex align-content-start flex-wrap border-s-thin"
      >
        <image-item
          v-for="(l, i) of items"
          :key="l.src"
          class="ma-1"
          :size="62"
          :url="l.src"
          @click="go(i)"
        />
      </div>
      <template v-if="items.length > 1">
        <div
          class="btns position-absolute top-0 left-0 h-100 d-flex flex-wrap align-content-center justify-center"
          style="width: 70px"
          @click="prev()"
        >
          <v-hover>
            <template #default="{ isHovering, props }">
              <v-btn
                v-bind="props"
                :color="isHovering ? 'warning' : ''"
                data-testid="image-preview-prev-button"
                :icon="mdiArrowLeft"
                variant="tonal"
              />
            </template>
          </v-hover>
        </div>
        <div
          class="btns position-absolute top-0 right-0 h-100 d-flex flex-wrap align-content-center justify-center"
          style="width: 70px"
          @click="next()"
        >
          <v-hover>
            <template #default="{ isHovering, props }">
              <v-btn
                v-bind="props"
                :color="isHovering ? 'warning' : ''"
                data-testid="image-preview-next-button"
                :icon="mdiArrowRight"
                variant="tonal"
              />
            </template>
          </v-hover>
        </div>
      </template>
    </div>
  </v-app>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { useSystemStateListener } from '@/composables/useSystemStateListener'
import { setToolbarConfig, type ToolbarConfigWithCallback } from '@/utils/toolbarHelper'
import {
  mdiArrowLeft,
  mdiArrowRight,
  mdiFaceRecognition,
  mdiInformation,
  mdiMagnifyMinus,
  mdiMagnifyPlus,
  mdiPanoramaHorizontalOutline,
  mdiPanoramaVariantOutline,
  mdiRotateRightVariant,
  mdiSelect,
  mdiTranslate,
  mdiViewComfyOutline
} from '@mdi/js'
import SuperImage from '@/components/image/super-image.vue'
// 启动系统状态监听器（保持原有行为）
useSystemStateListener()

type Item = {
  src: string
  name?: string
  path?: string
  size?: number
  format?: string
}

const items = reactive<Item[]>([])
const currentIndex = ref(0)
const active = reactive({
  list: false,
  info: false,
  tran: false,
  select: false
})

const meun = ref<ToolbarConfigWithCallback>({
  icon: false, // 不显示图标
  title: false, // 显示默认标题
  leftBtns: [
    {
      icon: mdiArrowLeft,
      color: '',
      title: '上一张',
      disabled: currentIndex.value === 0,
      onClick: () => {
        console.log('刷新按钮被点击')
        prev()
      },
      attrs: {
        'data-testid': 'image-preview-mdiArrowLeft'
      }
    },
    {
      icon: mdiArrowRight,
      color: '',
      title: '下一张',
      disabled: currentIndex.value === items.length - 1,
      onClick: () => {
        next()
      },
      attrs: {
        'data-testid': 'image-preview-mdiArrowRight'
      }
    },
    {
      icon: mdiViewComfyOutline,
      color: active.list ? 'warning' : '',
      title: '列表',
      disabled: items.length <= 1,
      onClick: showList,
      attrs: {
        'data-testid': 'image-preview-mdiViewComfyOutline'
      }
    },
    {
      icon: mdiMagnifyMinus,
      color: '',
      title: '缩小',
      onClick: zoomOut,
      attrs: {
        'data-testid': 'image-preview-mdiMagnifyMinus'
      }
    },
    {
      icon: mdiMagnifyPlus,
      color: '',
      title: '放大',
      onClick: zoomIn,
      attrs: {
        'data-testid': 'image-preview-mdiMagnifyPlus'
      }
    },
    {
      icon: mdiPanoramaHorizontalOutline,
      color: '',
      title: '原始尺寸',
      onClick: actualSize,
      attrs: {
        'data-testid': 'image-preview-mdiPanoramaHorizontalOutline'
      }
    },
    {
      icon: mdiPanoramaVariantOutline,
      color: '',
      title: '适应窗口',
      onClick: fitToWindow,
      attrs: {
        'data-testid': 'image-preview-mdiPanoramaVariantOutline'
      }
    },
    {
      icon: mdiInformation,
      color: '',
      title: '图片信息',
      onClick: showInfo,
      attrs: {
        'data-testid': 'image-preview-mdiInformation'
      }
    },
    {
      icon: mdiSelect,
      color: '',
      title: '框选',
      onClick: openSelect,
      attrs: {
        'data-testid': 'image-preview-mdiSelect'
      }
    },
    {
      icon: mdiFaceRecognition,
      color: '',
      title: '识别人脸',
      onClick: recognizeFaces,
      attrs: {
        'data-testid': 'image-preview-mdiFaceRecognition'
      }
    },
    {
      icon: mdiTranslate,
      color: '',
      title: '翻译',
      onClick: translation,
      attrs: {
        'data-testid': 'image-preview-mdiTranslate'
      }
    },
    {
      icon: mdiRotateRightVariant,
      color: '',
      title: '旋转图片',
      onClick: rotateImg,
      attrs: {
        'data-testid': 'image-preview-mdiRotateRightVariant'
      }
    }
  ]
})

const imgviewRef = ref<InstanceType<typeof SuperImage> | null>(null)

const currentItem = computed(() => items[currentIndex.value])

function resetView() {
  imgviewRef.value?.resetView()
}

function fitToWindow() {
  imgviewRef.value?.fitToWindow()
}

function actualSize() {
  imgviewRef.value?.actualSize()
}

function zoomIn() {
  imgviewRef?.value?.zoomIn()
}

function zoomOut() {
  imgviewRef?.value?.zoomOut()
}

function rotateImg() {
  imgviewRef.value?.rotateRight()
}

function openSelect() {
  active.select = !active.select
}

function recognizeFaces() {
  console.log('recognizeFaces')
}

function showInfo() {
  active.info = !active.info
}

function translation() {
  active.tran = !active.tran
}

function prev() {
  if (items.length <= 1) return
  currentIndex.value = (currentIndex.value - 1 + items.length) % items.length
}

function next() {
  if (items.length <= 1) return
  currentIndex.value = (currentIndex.value + 1) % items.length
}

function go(i: number) {
  currentIndex.value = i
}

function showList() {
  active.list = !active.list
  if (active.list) {
    // _pre_.tab.setWidth()
  }
}

function selectBox(b: { x: number; y: number; w: number; h: number }) {
  active.select = false
  console.log('选中区域', b)
}

// 键盘快捷键
function onKeyDown(e: KeyboardEvent) {
  switch (e.key) {
    case 'Escape': {
      break
    }
    case 'ArrowLeft': {
      prev()

      break
    }
    case 'ArrowRight': {
      next()

      break
    }
    case '+': {
      zoomIn()

      break
    }
    case '-': {
      zoomOut()

      break
    }
    default: {
      if (e.code === 'Space') {
        e.preventDefault()
        fitToWindow()
      }
    }
  }
}

function update(tab: F2.tab.Entity) {
  // console.log('update', tab)
  const data = tab.data as { list: any[]; index: number }
  const imgs = data.list.map(v => ({ ...v, src: v.file_path }))
  items.splice(0, items.length, ...imgs)
  currentIndex.value = data?.index ?? 0
  resetView()
}

onMounted(() => {
  const tab = _pre_.tab.getData()
  if (tab) update(tab)
  _pre_.tab.onUpdate(tab => {
    if (tab.data) update(tab as F2.tab.Entity)
  })
  window.addEventListener('keydown', onKeyDown)
})

onUnmounted(() => {
  window.removeEventListener('keydown', onKeyDown)
})

watch(currentIndex, () => {
  resetView()
})
// 设置工具栏配置
setToolbarConfig(meun.value)
watchEffect(() => {
  if (meun.value.leftBtns)
    for (const v of meun.value.leftBtns) {
      if (v.icon === mdiArrowLeft) v.disabled = currentIndex.value === 0
      if (v.icon === mdiArrowRight) v.disabled = currentIndex.value === items.length - 1
      if (v.icon === mdiViewComfyOutline) {
        v.disabled = items.length < 2
        v.color = active.list ? 'warning' : ''
      }
      if (v.icon === mdiInformation) v.color = active.info ? 'warning' : ''
      if (v.icon === mdiSelect) v.color = active.select ? 'warning' : ''
      if (v.icon === mdiTranslate) v.color = active.tran ? 'warning' : ''
    }
  setToolbarConfig(meun.value)
  // console.log('currentIndex', currentIndex.value, meun.value.leftBtns)
})
</script>

<style scoped>
.preview-root {
  position: fixed;
  inset: 0;
  display: flex;
}

.list-box {
  width: 220px;
  background: rgba(0, 0, 0, 0.6);
  height: 100vh;
}

.btns {
  opacity: 0;
}

.preview-root:hover .btns {
  opacity: 1;
}
</style>
